
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="padding: 36px">
        <el-steps :active="active" finish-status="success" simple>
          <el-step title="题库信息" />
          <el-step title="章节信息" />
        </el-steps>
        <div style="padding: 36px">
          <el-form
            v-show="active === 0"
            ref="form"
            :model="form"
            :rules="rules"
            label-width="80px"
            style="width: 40%"
          >
            <el-form-item label="题库名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="发布范围" prop="publish_range">
              <el-select
                v-model="form.publish_range"
                remote
                filterable
                placeholder="请选择地区"
                :remote-method="remoteMethod"
                :loading="selectload"
                style="width: 100%"
                @change="selectRegion"
              >
                <el-option
                  v-for="(item, index) in cityList"
                  :key="index"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="题库科目" prop="subject">
              <el-select v-model="form.subject" filterable placeholder="请选择科目" style="width: 100%">
                <el-option
                  v-for="(item, index) in subjectList"
                  :key="index"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="公开范围" prop="public_range">
              <el-select
                v-model="form.public_range"
                filterable
                placeholder="请选择范围"
                style="width: 100%"
              >
                <el-option label="普通" value="普通" />
                <el-option label="VIP" value="VIP" />
                <el-option label="SVIP" value="SVIP" />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="题库状态" prop="status">
              <el-switch
                v-model="form.status"
                :active-value="1"
                :inactive-value="-1"
                active-text="上架"
                inactive-text="下架"
              />
            </el-form-item> -->
            <el-form-item label="题库封面" prop="cover">
              <el-upload
                :headers="headers"
                class="avatar-uploader"
                :action="$uploadUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
<!--                <el-image v-if="form.cover" :src="getMediaUrl(form.cover)" class="upload-image" />-->
                <el-image v-if="form.cover" :src="form.cover" class="upload-image" />
                <i v-else class="el-icon-plus avatar-uploader-icon" />
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="题库描述" prop="description">
              <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-form>

          <div v-show="active === 1">
            <div style="display: flex; justify-content: flex-end;">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="updateChapter"
              >添加章节</el-button>
            </div>
            <div v-if="chapterData.length > 0">
              <QuestionChapter
                v-for="(item,index) in chapterData"
                :key="index"
                :chapter-key="index"
                :chapter-item="item"
                @dialogVisible="updateChapter"
                @say="parentSay"
              />
            </div>
            <el-empty v-else :image-size="150" />
          </div>
          <div style="float:right;margin-top: 20px">
            <el-button v-show="active !== 0" @click="lastStep">上一步</el-button>
            <el-button type="primary" @click="submitForm">{{ active === 1?'确认':'下一步' }}</el-button>
          </div>
        </div>
      </el-card>
      <el-dialog title="添加章节" :visible.sync="visible" destroy-on-close @closed="onClosed">
        <el-form ref="chapterForm" :model="chapterForm" :rules="rules" label-width="80px">
          <el-form-item label="章节名称" prop="name">
            <el-input v-model="chapterForm.name" />
          </el-form-item>
          <el-form-item label="公开状态" prop="is_free">
            <el-switch v-model="chapterForm.is_free" :active-value="1" :inactive-value="-1" />
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input v-model="chapterForm.note" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitChapterForm">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </BasicLayout>
</template>

<script>
import { getCity, getSubject, getSave } from '@/api/admin/sys-course'
import {
  addExercise,
  getExerciseDetails,
  editExercise,
  addChapter,
  editChapter,
  delChapter
} from '@/api/admin/sys-question'
import { getToken } from '@/utils/auth'
import QuestionChapter from './questionChapter'
export default {
  components: {
    QuestionChapter
  },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      active: 0,
      flagchange: 0,
      isChange: false,
      cityList: [],
      subjectList: [],
      form: {
        status: -1,
        subject: null
      },
      rules: {
        name: [
          { required: true, message: '题库名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '题库类型不能为空', trigger: 'blur' }
        ],
        // public_range: [
        //   { required: true, message: '公开范围不能为空', trigger: 'blur' }
        // ],
        subject: [{ required: true, message: '选择科目', trigger: 'blur' }],
        publish_range: [
          { required: true, message: '地区不能为空', trigger: 'blur' }
        ],
        // status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
        cover: [{ required: true, message: '上传封面', trigger: 'blur' }],
        is_free: [
          { required: true, message: '公开状态不能为空', trigger: 'blur' }
        ]
      },
      visible: false,
      chapterForm: {
        is_free: -1
      },
      chapterData: [],
      id: null,
      chapterKey: -1,
      selectload: false
    }
  },
  watch: {
    form: {
      deep: true,
      handler(val) {
        this.flagchange++
        if (this.flagchange > 1) {
          // 说明监听值有变化
          this.isChange = true // 弹框提示
        }
        if (val.province) {
          getSubject({ province: val.province }).then(res => {
            this.subjectList = res?.data || []
          })
        }
      }
    }
  },
  created() {
    this.getCity()
    if (this.$route.params.id) {
      /** 获取课程详情 */
      this.id = this.$route.params && Number(this.$route.params.id)
      getExerciseDetails(this.id).then(res => {
        const params = JSON.parse(JSON.stringify(res.data))
        delete params.exercises_ware_tree
        if (res.code === 200) {
          this.form = params
          this.chapterData = res.data?.exercises_ware_tree || []
        }
      })
    }
    if (this.$route?.params?.jump_id === 'subject') {
      this.active = 1
    }
  },
  methods: {
    selectRegion(val) {
      this.form.subject = null
      getSubject({ province: val }).then(res => {
        this.subjectList = res?.data || []
      })
    },
    getCity() {
      getCity().then(res => {
        this.cityList = res?.data || []
      })
    },
    // 更新章节
    updateChapter(value) {
      if (value.type === 'delete') {
        if (value?.chapterItem?.id) {
          this.$confirm('是否确认删除', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              delChapter(value?.chapterItem?.id).then(res => {
                if (res.code === 200) {
                  this.chapterData = this.chapterData?.filter(
                    (item, index) => index !== value?.chapterKey
                  )
                }
              })
            })
            .catch(function() {})
          return
        }
        this.chapterData = this.chapterData?.filter(
          (item, index) => index !== value?.chapterKey
        )
      } else {
        this.visible = true
        if (value?.chapterItem) {
          this.chapterForm = value?.chapterItem
          this.chapterKey = value?.chapterKey
        }
      }
    },
    cancel() {
      this.visible = false
      this.onClosed()
    },
    onClosed() {
      this.chapterForm = {}
      this.resetForm('chapterForm')
    },
    submitChapterForm() {
      this.$refs['chapterForm'].validate(valid => {
        if (valid && this.chapterKey !== -1 && this.chapterForm.id) {
          editChapter(this.chapterForm).then(response => {
            this.chapterData = this.chapterData.map((item, index) =>
              index === this.chapterKey
                ? JSON.parse(JSON.stringify(this.chapterForm))
                : item
            )
            this.visible = false
            this.chapterKey = -1
          })
        } else if (valid && this.chapterKey === -1) {
          addChapter({
            ...this.chapterForm,
            question_bank_id: this.id,
            pid: 0
          }).then(res => {
            this.chapterData.push({
              ...this.chapterForm,
              id: res.data,
              question_bank_id: this.id,
              children: []
            })
            this.visible = false
          })
        }
      })
    },
    parentSay(msg) {
      this.chapterData = this.chapterData.map(item =>
        item.name === msg.name ? msg : item
      )
    },
    // 上一步
    lastStep() {
      if (this.active-- < 1) return (this.active = 0)
    },
    // 下一步
    submitForm() {
      if (this.active === 0) {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.$route.params.id && this.isChange) {
              editExercise({ ...this.form, id: this.id, status: -1 }).then(res => {
                if (res.code === 200) {
                  this.msgSuccess(res.msg)
                  this.active++
                } else {
                  this.msgError(res.msg)
                }
              })
            } else if (this.$route.params.id) {
              this.active++
            } else {
              addExercise({ ...this.form, status: -1 }).then(res => {
                if (res.code === 200) {
                  this.id = res.data
                  this.msgSuccess(res.msg)
                  this.active++
                } else {
                  this.msgError(res.msg)
                }
              })
            }
          } else {
            return
          }
        })
      } else if (this.active === 1) {
        if (this.id) {
          getSave({
            link_type: 2,
            obj_id: this.id
          }).then(res => {})
        }
        this.$router.push('/admin/sys-question-back/practice')
      }
    },
    handleAvatarSuccess(res) {
      this.$set(this.form, 'cover', res.data.full_path)
    },

    beforeAvatarUpload(file) {
      const isLt05M = file.size / 1024 / 1024 < 0.5
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt05M) {
        this.$message.error('上传头像图片大小不能超过 500k!')
      }
      return !isJPG && isLt05M
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.addsonchapter {
  border: 1px solid #c0c4cc;
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  color: #3d64d4;
}
</style>
